import 'dart:io';

import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:star_author/config/app.dart';
import 'package:star_author/env/env_banner.dart';
import 'package:star_author/provider/index.dart';
import 'package:star_author/provider/searchHistory.dart';
import 'package:star_author/route/getx_router.dart';
import 'package:star_author/utils/media_recorder_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provider/provider.dart';
import 'package:skeletons/skeletons.dart';

import 'CustomNavigatorObserver.dart';
import 'config/base_configuration.dart';
import 'deer/routers/not_found_page.dart';
import 'deer/routers/routers.dart';
import 'views/anchor/home_page.dart';
import 'views/stream/overlay_video.dart';
import 'views/stream/stream_pip_controller.dart';
import 'views/stream/stream_rtc_controller.dart';

class AppInit extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return EvnBanner(
      child: ScreenUtilInit(
        ///初始化设计图尺寸
        designSize: Size(375, 667),
        minTextAdapt: true,
        builder: (ctx, child) => MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (ctx) => UserProvider()),
            ChangeNotifierProvider(create: (ctx) => ConfigProvider()),
            ChangeNotifierProvider(create: (ctx) => SearchHistoryProvider()),
          ],
          child: SkeletonTheme(
            // themeMode: ThemeMode.light,
            shimmerGradient: LinearGradient(
              colors: [
                Color(0xffeeeeee),
                Color(0xffeeeeee),
                Color(0xffeeeeee),
                Color(0xffeeeeee),
                Color(0xffeeeeee),
              ],
              stops: [
                0.1,
                0.3,
                0.5,
                0.7,
                0.9,
              ],
              tileMode: TileMode.repeated,
            ),
            darkShimmerGradient: LinearGradient(
              colors: [
                Color(0xffeeeeee),
                Color(0xffeeeeee),
                Color(0xffeeeeee),
                Color(0xffeeeeee),
                Color(0xffeeeeee),
              ],
              stops: [
                0.0,
                0.2,
                0.5,
                0.8,
                1,
              ],
              begin: Alignment(-2.4, -0.2),
              end: Alignment(2.4, 0.2),
              tileMode: TileMode.clamp,
            ),
            themeMode: ThemeMode.light,
            child: MyApp(),
          ),
        ),
      ),
    );
  }
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //必须放在顶层 不然会出现多个 导致多次进入直播间页面进入会有问题
    Get.put(StreamRTCController(clientRole: ClientRole.Audience));
    Get.put(StreamPipController());
    MediaRecorderUtil.getStoragePath().then((value) {
      App.mDir = value + 'cache/';
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      builder: EasyLoading.init(builder: (BuildContext context, Widget? child) {
        return MediaQuery(
          //设置文字大小不随系统设置改变
          data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
          child: Builder(
              builder: (context) => OverlaySupport.global(child: child!)),
        );
      }),
      title: '直播LIVE',
      navigatorKey: App.materialKey,
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        textSelectionTheme: TextSelectionThemeData(
          cursorColor: Color(0xFF333333),
        ),
        platform: TargetPlatform.iOS,
        backgroundColor: Color(0xFFF5F5F5),
      ),
      home: HomePage(),
      defaultTransition: Transition.cupertino,
      navigatorObservers: [
        GLObserver(), //全局监听路由
        CustomNavigatorObserver.instance
      ],
      getPages: GetXRouter.getPages,
      onGenerateRoute: Routes.router.generator,
      /// 因为使用了fluro，这里设置主要针对Web
      // onUnknownRoute: (_) {
      //   return MaterialPageRoute<void>(
      //     builder: (BuildContext context) => const NotFoundPage(),
      //   );
      // },
    );
  }
}

class GLObserver extends NavigatorObserver {
// 添加导航监听后，跳转的时候需要使用Navigator.push路由
  @override
  void didPush(Route route, Route? previousRoute) {
    super.didPush(route, previousRoute);
    String previousName = route.settings.name ?? "";
    List needHidden = [
      '/OpenLive',
      "/StreamPage",
      "/GoldStreamPage",
    ];
    if (needHidden.contains(previousName)) {
      if (StreamConf.uid != -1) {
        if (Platform.isAndroid) {
        } else {
          if (Get.find<StreamPipController>().pipFlutterPlayerController !=
              null) {
            Get.find<StreamPipController>()
                .pipFlutterPlayerController!
                .isPictureInPictureSupported()
                .then((value) {
              if (!value) {
                OverlayVideo.disPlay();
              }
            });
          }
        }
      }
    }
  }

  @override
  void didPop(Route route, Route? previousRoute) {
    super.didPop(route, previousRoute);
    if (EasyLoading.isShow) {
      EasyLoading.dismiss();
    }
    String previousName = route.settings.name ?? "";
    List needHidden = ["/StreamPage", "/GoldStreamPage", "/IndexPage"];
    if (needHidden.contains(previousName)) {
      if (StreamConf.uid != -1 && StreamConf.isShowVideo) {
        if (Platform.isIOS) {
          Get.find<StreamPipController>()
              .initStreamPipController(StreamConf.channelModel!.pullUrl);
        }
      }
    }
  }
}
